package com.hmdp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpSession;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import lombok.extern.slf4j.Slf4j;

import static com.hmdp.constants.CommonConst.USER_NICK_PRE;
import static com.hmdp.utils.RedisConstants.LOGIN_CODE_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_CODE_TTL;
import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_USER_TTL;
import static com.hmdp.utils.RegexPatterns.PHONE_REGEX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        // 校验手机号
        if (!ReUtil.isMatch(PHONE_REGEX, phone)) {
            return Result.fail("手机号码输入有误");
        }
        // 生成验证码
        String code = RandomUtil.randomNumbers(6);
        log.info("验证码为: " + code);
        // 保存验证码到redis中
        redisTemplate.opsForValue().set(LOGIN_CODE_KEY, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        // 保存验证码到session域中
//        session.setAttribute(CODE, code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        // 获取用户手机号码
        String phone = loginForm.getPhone();
        // 校验手机号
        if (!ReUtil.isMatch(PHONE_REGEX, phone)) {
            return Result.fail("手机号码输入有误");
        }
        // 获取验证码
        String code = redisTemplate.opsForValue().get(LOGIN_CODE_KEY);
//        String attribute = (String) session.getAttribute(CODE);
        if (!loginForm.getCode().equals(code)) {
            return Result.fail("验证码错误");
        }
        // 查询用户是否存在不村存在创建一个用户
        User user = this.query().eq("phone", phone).one();
        if (ObjectUtil.isEmpty(user)) {
            user = new User();
            // 添加一个用户
            BeanUtil.copyProperties(loginForm, user);
            user.setNickName(USER_NICK_PRE + RandomUtil.randomString(6));
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            boolean save = save(user);
            if (!save) {
                return Result.fail("用户登录失败");
            }
        }
        // 生成一个随机token
        String token = UUID.randomUUID().toString();
        // 保存到redis中,用hash结构
        UserDTO userDTO = BeanUtil.toBean(user, UserDTO.class);
        Map<String, Object> beanMap = new HashMap<>();
        BeanUtil.beanToMap(userDTO, beanMap,
                CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        redisTemplate.opsForHash().putAll(LOGIN_USER_KEY + token, beanMap);
        redisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.SECONDS);
//        session.setAttribute(USER, BeanUtil.copyProperties(user, UserDTO.class));
        return Result.ok(token);
    }
}
